/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
// map
var twoSum = function (nums, target) {
  let map = new Map();
  // 使用 for 循环可以在找到答案时直接返回
  for (let index = 0; index < nums.length; index++) {
    let item = nums[index];
    let otherVal = target - item;
    if (map.has(otherVal)) {
      return [map.get(otherVal), index];
    }
    map.set(item, index);
  }
  return [];
};

console.log("map", twoSum([2, 11, 7, 15], 9));

var twoSum1 = function (nums, target) {
  // 先保存每个元素的原始索引
  let indexedNums = nums.map((num, index) => ({ num, index }));

  // 按照元素值升序排序
  indexedNums.sort((a, b) => a.num - b.num);

  let left = 0;
  let right = indexedNums.length - 1;

  while (left < right) {
    let sum = indexedNums[left].num + indexedNums[right].num;
    if (sum === target) {
      // 返回原始索引
      return [indexedNums[left].index, indexedNums[right].index];
    } else if (sum < target) {
      left++;
    } else {
      right--;
    }
  }

  return [];
};

console.log(twoSum1([2, 11, 7, 15], 9));
